import 'package:casdon/modules/me/data/model/browsing_life_history_model.dart';
import 'package:casdon/modules/me/domain/states/browsing_life_history_state.dart';
import 'package:casdon/modules/me/domain/usecase/browsing_life_history_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class BrowsingLifeHistoryNotifier
    extends AutoDisposeAsyncNotifier<BrowsingLifeHistoryState> {
  int pageNum = 1;
  final int pageSize = 20;
  bool _isRefreshing = false;
  bool _isLoadingMore = false;

  @override
  Future<BrowsingLifeHistoryState> build() async {
    pageNum = 1;
    _isRefreshing = false;
    _isLoadingMore = false;
    return await _fetchData();
  }

  Future<void> refresh() async {
    // 如果正在刷新或加载更多，则直接返回
    if (_isRefreshing || _isLoadingMore) return;
    
    try {
      _isRefreshing = true;
      pageNum = 1;
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    } finally {
      _isRefreshing = false;
    }
  }

  Future<void> loadMore() async {
    // 如果正在刷新、正在加载更多、或者没有数据，则直接返回
    if (_isRefreshing || _isLoadingMore || state.isLoading || !state.hasValue) {
      return;
    }
    
    try {
      _isLoadingMore = true;
      pageNum++;
      final newState = await _fetchData();
      final currentData = state.value!.data;
      // 去重：只添加不存在的 item（基于 id）
      final existingIds = currentData.map((e) => e.id).toSet();
      final uniqueNewData = newState.data
          .where((item) => !existingIds.contains(item.id))
          .toList();
      final newData = currentData + uniqueNewData;
      state = AsyncValue.data(
        BrowsingLifeHistoryState(data: newData, totalSize: newState.totalSize),
      );
    } catch (e, st) {
      pageNum--; // 回滚页码
      state = AsyncValue.error(e, st);
    } finally {
      _isLoadingMore = false;
    }
  }

  Future<BrowsingLifeHistoryState> _fetchData() async {
    final ret = await ref
        .read(browsingLifeHistoryUsecaseProvider)
        .execute(pageNum: pageNum, pageSize: pageSize);

    final models = BrowsingLifeHistoryModel.listFromApi(ret.rows);

    return BrowsingLifeHistoryState(data: models, totalSize: ret.total);
  }
}

final browsingLifeHistoryNotifierProvider =
    AutoDisposeAsyncNotifierProvider<
      BrowsingLifeHistoryNotifier,
      BrowsingLifeHistoryState
    >(BrowsingLifeHistoryNotifier.new);
